<template>
    <div class="container">
        <el-input v-model="input" style="width: 240px" placeholder="输入用户名" />
        <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUser">查询</el-button>
        <el-button style="width: 6rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="newUser"   v-if="hasPermission(authStore.permissions,25)">新建DJI用户</el-button>
        <!-- 点击新建角色打开 -->
        <el-dialog v-model="visible" :show-close="false" width="800">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div>新建DJI用户</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div style="display: flex;"></div>
      <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
          <span style="color: red;">*</span>用户名:
        </div>
        <el-input style="width: 240px" v-model="userName" ></el-input>
      </div>
      <p v-if="djiUserErrors.userName" style="color: red; font-size: 12px; margin-left: 10rem;">用户名不能为空</p>
        
        <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
        <span style="color: transparent;">*</span>
          密码：
        </div>
        <el-input style="width: 240px" v-model="passWord"></el-input>
        </div>
        <p v-if="djiUserErrors.passWord" style="color: red; font-size: 12px; margin-left: 10rem;">密码不能为空</p>

      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sumbitMessage()">确定</el-button>
        </div>
      </div>
    </el-dialog>


    <el-table :data="displayedData" style="width: 80%; margin-top: 3rem;">
  <el-table-column label="序号" width="100">
    <template #default="{ row, $index }">
      <span v-if="row.username">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
      <span v-else  style="color:black;opacity: 0;">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>

    </template>
  </el-table-column>

  <el-table-column prop="role.username" label="用户名" width="150">
    <template #default="{ row }">
      <span  style="color: black;">{{ row.username }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.password" label="密码" width="150">
    <template #default="{ row }">
      <span  style="color: black;">{{ row.password }}</span>

    </template>
  </el-table-column>

  <el-table-column prop="role.createTime" label="创建时间" width="200">
    <template #default="{ row }">
      <span  style="color: black;">{{ row.createTime }}</span>

    </template>
  </el-table-column>
  
  <el-table-column fixed="right" label="操作" min-width="200">
    <template #default="{ row }">
      <div v-if="row.id">
        <el-button link type="primary" size="small" @click="deleteTower(row)"   v-if="hasPermission(authStore.permissions,26)" style="color:#f56c6c;">删除</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

    </div>


    <el-dialog v-model="deleteVisible" title="提示" width="500" center>
            <span>
              是否需要删除DJI账号 "{{deleteItem?.username}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible = false">取消</el-button>
              <el-button type="primary" @click="handleClick()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>
</template>

<script lang="ts" setup>
    import { CircleCloseFilled } from '@element-plus/icons-vue';
    import { ref ,onMounted ,nextTick ,onUnmounted } from 'vue'
    import request from '@/utils/request';
    import { useAuthStore } from '@/stores/user';
    import showMessage from '@/utils/showMessage';
    import { hasPermission } from '@/utils/permissionUtils';

    const authStore = useAuthStore();//使用store仓库进行数据管理

    const tableData = ref([]); // 原始数据
    const displayedData = ref([]); // 当前页显示的数据
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页条数
    const total = ref(0); // 总条数
    const input = ref('')
    const userName = ref('')
    const passWord = ref('')
    const visible = ref(false)
    // 新建角色
    const newUser= () => {
      djiUserErrors.value = {
      userName: false,
      passWord: false,
    };

      visible.value = true;
      userName.value = ''
      passWord.value = ''
    }

    const filterUser = () => {
      const  username = input.value || ''
      const formData = new FormData();
      formData.append('username', username)
          request.post("/resource/getDJIUserByCondition",formData).then(
            (res)=>{
              if(res.status == 200){
                tableData.value = res.data
                total.value = res.data.length;
                updateDisplayedData();
            }
            }
          )
    }
    // 表单验证校验
    const djiUserErrors = ref({
      userName: false,
      passWord: false,
    });

    const validateDjiUser = () => {
  let isValid = true;
  if (!userName.value.trim()) {
    djiUserErrors.value.userName = true;
    isValid = false;
  } else {
    djiUserErrors.value.userName = false;
  }

  if (!passWord.value.trim()) {
    djiUserErrors.value.passWord = true;
    isValid = false;
  } else {
    djiUserErrors.value.passWord = false;
  }
  return isValid;
};
        // 删除逻辑

    const deleteVisible = ref(false)
    const deleteItem = ref()
    const deleteTower = (row:any) => {
      deleteVisible.value = true
      deleteItem.value = row
    }
    const handleClick =() => {
        request.post("/resource/deleteDJIUserByID",
          {id:deleteItem.value.id}
        ).then(
          (res)=>{
            showMessage(res)
            if(res.data.status == 'success'){
            //删除用户日志 
              request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"删除DJI账号",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              })
              // 获取所有用户信息
              getAllUser()
              deleteVisible.value = false
            }
          }
        )
    }
// 新增dji用户
const sumbitMessage =() => {
  if (!validateDjiUser()) return;
    const username = userName.value;//用户名
    const password = passWord.value;//用户名
    request.post('/resource/insertDJIUser',{
        username,
        password
    }).then((res)=>{
      if(res.data.status == 'success'){
  
        visible.value = false
        userName.value = '',
        passWord.value = '',

         // 新建用户
         request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"新增DJI成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              })

        getAllUser()
      }
    })
  }

// 获取全部用户信息
const getAllUser = () => {
  request.get('/resource/getAllDJIUser').then(
    (res)=>{
      if(res.data){
        tableData.value = res.data
        total.value = res.data.length;
        updateDisplayedData();
      }
    }
  )
}

// 更新显示的数据
const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};


  const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 10 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllUser()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});

</script>

<style scoped>
.container {
    width: 100%;
    height: calc(100vh - 100px);
    display: block;
    padding: 20px;
    box-sizing: border-box;
}
.container-head {
    display: flex
} 
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.input-text {
    width: 20%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.input-text1 {
    width: 10%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.selected-tab {
  background-color: #409eff;
  color: white;
}
.empty-row {
  background-color: #f5f7fa;
  color: gray;
  text-align: center;
}
</style>